<?php
// 1908080121李定邦、1902030115李龙烽
namespace app\admin\controller;

use app\admin\validate\AdminUser;
use app\BaseController;
use app\Request;
use think\exception\ValidateException;

class Admin extends BaseController
{

    public function login(Request $request) {
        if ($request->isPost()) {
            $username = $this->request->post('username', '', 'trim');
            $password = $this->request->post('password', '', 'trim');
            $code     = $this->request->post('code', '', 'trim');
            $ck_data  = [
                'username' => $username,
                'password' => $password,
                'code'     => $code,
            ];
            try {
                validate(AdminUser::class)
                    ->scene('login')
                    ->check($ck_data);
            } catch (ValidateException $e) {
                $error = $e->getError();
                $this->error($error, '/login');
            }
            $res = app('db')->name('admin_user')->where('username',  $username)
                ->where('password', md5($password))->find();
            $res && app('session')->set('login_admin_id', $res['id']);
            !empty($res) ? $this->success('登录成功', '/index') : $this->error('账户或密码错误');
        } else {
            $src = captcha_src('');
            return app('view')->fetch('', ['src' => $src]);
        }
    }

    /**
     * 注销
     * @return void
     */
    public function logout()
    {
        $this->checkIsAdminLogin();
        app('session')->delete('login_admin_id');
        $this->success('注销成功！', '/login');
    }

    /**
     * 修改密码
     * @return void
     */
    public function password()
    {
        $this->checkIsAdminLogin();
        $info = app('db')->name('admin_user')->where('id', session('login_admin_id'))->find();
        if ($this->request->isPost()) {
            $password             = $this->request->post('password');
            $new_password         = $this->request->post('new_password');
            $new_confirm_password = $this->request->post('new_confirm_password');
            if ($info['password'] != md5($password)) {
                $this->error('旧密码不正确', '');
            }
            if ($new_confirm_password != $new_password) {
                $this->error('新密码输入不一致', '');
            }
            app('session')->delete('login_admin_id');
            app('db')->name('admin_user')->where('id', session('login_admin_id'))->update(['password' => md5($new_password)]);
            $this->success('修改成功，请重新登录！', '/login');
        }

        return app('view')->fetch('pass', ['info' => $info]);
    }
}
